<?php

namespace app\api\controller;

use think\Controller;

class Sleep extends Controller
{
    public $pagesize = 10;
    public $expire = 36000;//缓存过期时间
    public $selectDays = 30;//查询最近多少天的数据

    /**
     * 上传 用户睡眠报告
     */
    public function notice()
    {
        $auth = trim(input("request.auth"));//用户auth
        $dataid = trim(input("request.dataid"));//购买数量
        $devtype = trim(input("request.devtype"));//购买数量
        if (empty($devtype)) {
            $devtype = 0;
        }

        $userInfo = checkLoginExp($auth);

        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }
        if (empty($dataid)) {
            $return = ['err' => 3, 'msg' => '参数错误', 'devMsg' => '获取失败，参数错误[dataid]'];
            return json($return);
        }

        //增加一个日志表，确保队列redis失败后有记录可查询
        addSleepApiLog($userInfo['id'], $dataid, $devtype);
        //向队列中增加一个获取报告的任务
        $param = array('uid' => $userInfo['id'], 'dataid' => $dataid,'ty'=>$devtype);
        addSleepReportQueue($param);


        $return = ['err' => 0, 'msg' => '操作成功', 'dataid' => $dataid, 'devMsg' => '操作成功'];
        return json($return);
    }

    public function noticePre()
    {
        $auth = trim(input("request.auth"));//用户auth
        $device = trim(input("request.device"));//设备序列号
        $testid = trim(input("request.testid"));//手机端传给设备的当前报告标志testid
        $devtype = trim(input("request.devtype"));//设备类型 0 100b   ，1 100c
        if (empty($devtype)) {
            $devtype = 0;
        }

        $userInfo = checkLoginExp($auth);

        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }
        if (empty($device)) {
            $return = ['err' => 3, 'msg' => '参数错误', 'devMsg' => '获取失败，参数错误[device]'];
            return json($return);
        }

        if (empty($testid)) {
            $return = ['err' => 3, 'msg' => '参数错误', 'devMsg' => '获取失败，参数错误[testid]'];
            return json($return);
        }
        //增加一个日志表，确保队列redis失败后有记录可查询
        addSleepApiLogPre($userInfo['id'], $device, $testid, $devtype);
        //向队列中增加一个获取报告的任务
        $param = array('uid' => $userInfo['id'], 'device' => $device,'testid'=>$testid,'ty'=>$devtype);
        addSleepReportQueuePre10($param);

        $return = ['err' => 0, 'msg' => '操作成功'];
        return json($return);
    }



    public function noticeGetFileStatus()
    {
        $auth = trim(input("request.auth"));//用户auth
        $device = trim(input("request.device"));//设备序列号
        $testid = trim(input("request.testid"));//手机端传给设备的当前报告标志testid
        $devtype = trim(input("request.devtype"));//设备类型 0 100b   ，1 100c
        if (empty($devtype)) {
            $devtype = 0;
        }

        $userInfo = checkLoginExp($auth);

        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }
        if (empty($device)) {
            $return = ['err' => 3, 'msg' => '参数错误', 'devMsg' => '获取失败，参数错误[device]'];
            return json($return);
        }

        if (empty($testid)) {
            $return = ['err' => 3, 'msg' => '参数错误', 'devMsg' => '获取失败，参数错误[testid]'];
            return json($return);
        }
        //增加一个日志表，确保队列redis失败后有记录可查询
        addSleepApiLogPre($userInfo['id'], $device, $testid, $devtype);
        //向队列中增加一个获取报告的任务
        $param = array('uid' => $userInfo['id'], 'device' => $device,'testid'=>$testid,'ty'=>$devtype);
        addSleepReportQueuePre($param);


        $return = ['err' => 0, 'msg' => '操作成功'];
        return json($return);
    }

    /**
     * 小程序通知 获取报告接口
     * @return \think\response\Json
     */
    public function wechatNotice()
    {
        $access_token = trim($_REQUEST['access_token']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($_hosp)) {
            $return['err'] = 1;
            $return['msg'] = '参数错误[_hosp]';
            return json($return);
        }
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {

            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;

        }
        $dataid = trim(input("request.dataid"));//购买数量

        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }
        if (empty($dataid)) {
            $return = ['err' => 3, 'msg' => '参数错误', 'devMsg' => '获取失败，参数错误[dataid]'];
            return json($return);
        }
        $devtype = trim(input("request.devtype"));//购买数量
        if (empty($devtype)) {
            $devtype = 0;
        }
        //增加一个日志表，确保队列redis失败后有记录可查询
        addSleepApiLog($userInfo['id'], $dataid, $devtype);
        //向队列中增加一个获取报告的任务
        $param = array('uid' => $userInfo['id'], 'dataid' => $dataid,'ty'=>$devtype);
        addSleepReportQueue($param);
        $return = ['err' => 0, 'msg' => '操作成功', 'dataid' => $dataid, 'devMsg' => '操作成功'];
        return json($return);
    }

    /**
     * 获取我的报告列表接口
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function wechatLists()
    {
        $access_token = trim($_REQUEST['access_token']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($_hosp)) {
            $return['err'] = 1;
            $return['msg'] = '参数错误[_hosp]';
            return json($return);
        }
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {

            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;

        }
        $pagesize = trim(input("pagesize"));//每页条数

        if (!empty($pagesize)) {
            $this->pagesize = $pagesize;
        }
        $sleepModel = new \app\admin\model\Sleep();


        $w = array(
            'uid' => $userInfo['id'],
            'summary_data_ok' => 1,
            'curves_data_ok' => 1,
        );
        $lists = $sleepModel->lists($w, $this->pagesize, '*', "id desc");


        foreach ($lists['data'] as $key => $val) {
            if ($val['curves_data']) {
                $val['curves_data'] = json_decode($val['curves_data'], true);
            } else {
                $val['curves_data'] = array();
            }

            if ($val['summary_data']) {
                $val['summary_data'] = json_decode($val['summary_data'], true);
            } else {
                $val['summary_data'] = array();
            }
            if ($val['curves_data']['data_sleep_status']) {
                $val['deal_data_sleep_status'] = $this->makeDataSleepStatus($val['curves_data']['data_sleep_status']);
            } else {
                $val['deal_data_sleep_status'] = array();
            }
            $lists['data'][$key] = $val;
        }

        $lists['data'] = changeUidToUserinfoForLists($lists['data'], 'uid');
        $return = ['err' => 0, 'msg' => '操作成功', 'data' => $lists, 'devMsg' => '操作成功'];
        return json($return);
    }

    /**
     * 保存app端检测睡眠数据
     */
    public function appMonitor()
    {
        $auth = trim(input("request.auth"));//用户auth
        $jsonData = trim(input("request.data"));//购买数量
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '操作失败,未登录', 'devMsg' => '操作失败，参数错误[auth]'];
            return json($return);
        }
        if (empty($jsonData)) {
            $return = ['err' => 3, 'msg' => '参数错误', 'devMsg' => '获取失败，参数错误[data]'];
            return json($return);
        }

        $jsonArr = json_decode($jsonData, true);
        if (empty($jsonArr)) {
            $return = ['err' => 4, 'msg' => '参数错误', 'devMsg' => '获取失败，参数错误[data]'];
            return json($return);
        }


        if (empty($jsonArr['date'])) {
            $return = ['err' => 3, 'msg' => '数据格式不正确[日期]', 'devMsg' => '数据格式不正确'];
            return json($return);
        }
        $year = substr($jsonArr['date'], 0, 4);
        $month = substr($jsonArr['date'], 4, 2);
        $day = substr($jsonArr['date'], 6, 2);
        $rid = $jsonArr['id'];

        if (empty($rid)) {
            $return = ['err' => 3, 'msg' => '数据格式不正确[id]', 'devMsg' => '数据格式不正确'];
            return json($return);
        }

        $inputData = array(
            'year' => $year,
            'month' => $month,
            'day' => $day,
            'year_month_day' => $year . "-" . $month . "-" . $day,
            'uid' => $userInfo['id'],
            'data' => $jsonData,
            'rid' => $rid,
            'ctime' => time()
        );

        $model = new \app\admin\model\SleepApp();
        $res = $model->add($inputData);
        if ($res) {
            $return = ['err' => 0, 'msg' => '操作成功', 'devMsg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 1, 'msg' => '操作失败', 'devMsg' => '操作失败'];
            return json($return);
        }

    }


    public function report()
    {
        $uid = trim(input("request.uid"));//用户auth
        $rid = trim(input("request.id"));//用户数据ID

        if (empty($uid)) {
            $return = ['err' => 1, 'msg' => '参数错误', 'devMsg' => '参数错误'];
            return json($return);
        }
        if (empty($rid)) {
            $return = ['err' => 2, 'msg' => '参数错误', 'devMsg' => '参数错误'];
            return json($return);
        }
        $UserInfo = getUserInfoForID($uid);
        if (empty($UserInfo)) {
            $return = ['err' => 3, 'msg' => '参数错误', 'devMsg' => '参数错误'];
            return json($return);
        }

        $model = new \app\admin\model\SleepApp();

        $reportInfo = $model->getDataForWhere(array('uid' => $uid, 'rid' => $rid), '*', 'id desc');
        if (empty($reportInfo)) {
            $return = ['err' => 5, 'msg' => '未找到相关的睡眠数据', 'devMsg' => ''];
            return json($return);
        }


        $data = array();
        $data['UserInfo'] = array(
            'uname' => $UserInfo['uname'],
            'nickname' => $UserInfo['nickname'],
            'head' => $UserInfo['head'],
            'sex' => $UserInfo['sex'],
            'bday' => $UserInfo['bday'],
        );


        $data['report'] = json_decode($reportInfo['data'], true);

        $return = ['err' => 0, 'msg' => '获取成功', 'data' => $data];
        return json($return);
    }

    /**
     * 获取睡眠海报接口
     */
    public function getPoster()
    {
        $model = new \app\admin\model\Poster();
        $list = $model->getDataForWheres(array('is_delete' => 0, 'stats' => 0), 'name,img,start,end', 'id asc');
        $return = ['err' => 0, 'msg' => '获取成功', 'data' => $list];
        return json($return);
    }

    /**
     * 获取我的最近几个的报告
     * @return \think\response\Json
     */
    public function myLists()
    {
        $limitNum = 3;//默认获取几个报告的数据
        $auth = trim(input("request.auth"));//用户auth
        $num = trim(input("request.num"));//用户auth
        if (!empty($num)) {
            $limitNum = $num;
        }
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }

        $sleepModel = new \app\admin\model\Sleep();
        $w = array(
            'uid' => $userInfo['id'],
            'summary_data_ok' => 1,
            'curves_data_ok' => 1,
        );
        $lists = $sleepModel->getDataForWheres($w, "*", "id desc", $limitNum);

        $rLists = array();
        foreach ($lists as $key => $val) {
            if ($val['curves_data']) {
                $val['curves_data'] = json_decode($val['curves_data'], true);
            } else {
                $val['curves_data'] = array();
            }

            if ($val['summary_data']) {
                $val['summary_data'] = json_decode($val['summary_data'], true);
            } else {
                $val['summary_data'] = array();
            }
            if ($val['curves_data']['data_sleep_status']) {
                $val['deal_data_sleep_status'] = $this->makeDataSleepStatus($val['curves_data']['data_sleep_status']);
            } else {
                $val['deal_data_sleep_status'] = array();
            }
            $rLists[] = $val;
        }

        $return = ['err' => 0, 'msg' => '操作成功', 'data' => $rLists, 'devMsg' => '操作成功'];
        return json($return);
    }


    /**
     * 获取我的最近几个报告接口
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function wechatMyNearestSleep()
    {
        $limitNum = 3;//默认获取几个报告的数据

        $num = trim(input("request.num"));//用户auth
        if (!empty($num)) {
            $limitNum = $num;
        }
        $access_token = trim($_REQUEST['access_token']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($_hosp)) {
            $return['err'] = 1;
            $return['msg'] = '参数错误[_hosp]';
            return json($return);
        }
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {

            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;

        }

        $sleepModel = new \app\admin\model\Sleep();
        $w = array(
            'uid' => $userInfo['id'],
            'summary_data_ok' => 1,
            'curves_data_ok' => 1,
        );
        $lists = $sleepModel->getDataForWheres($w, "*", "id desc", $limitNum);

        $rLists = array();
        foreach ($lists as $key => $val) {
            if ($val['curves_data']) {
                $val['curves_data'] = json_decode($val['curves_data'], true);
            } else {
                $val['curves_data'] = array();
            }

            if ($val['summary_data']) {
                $val['summary_data'] = json_decode($val['summary_data'], true);
            } else {
                $val['summary_data'] = array();
            }
            if ($val['curves_data']['data_sleep_status']) {
                $val['deal_data_sleep_status'] = $this->makeDataSleepStatus($val['curves_data']['data_sleep_status']);
            } else {
                $val['deal_data_sleep_status'] = array();
            }
            $rLists[] = $val;
        }

        $return = ['err' => 0, 'msg' => '操作成功', 'data' => $rLists, 'devMsg' => '操作成功'];
        return json($return);
    }

    private function makeDataSleepStatus($data_sleep_status)
    {
        $number = 5;//用于翻转的数
        $makeDataSleepStatus = array();
        $length = count($data_sleep_status);
        $step = 0;
        if ($length <= 10) {
            $step = 1;
        } else if ($length <= 50) {
            $step = 3;
        } else if ($length <= 100) {
            $step = 5;
        } else if ($length <= 200) {
            $step = 10;
        } else if ($length <= 400) {
            $step = 15;
        } else {
            $step = 20;
        }

        $curr = 0;
        while (true) {
            $curr = $curr + $step;
            if ($curr >= $length) {
                break;
            }
            if ($data_sleep_status[$curr] <= 0) {
                $makeDataSleepStatus[] = 0;
            } else {
                $makeDataSleepStatus[] = $number - $data_sleep_status[$curr];
            }

        }

        return $makeDataSleepStatus;
    }

    /**
     * 获取我的一个报告详情数据
     * @return \think\response\Json
     */
    public function info()
    {
        $auth = trim(input("request.auth"));//用户auth
        $id = trim(input("request.id"));//报告ID
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }

        if (empty($id)) {
            $return = ['err' => 1, 'msg' => '获取失败,参数错误', 'devMsg' => '获取失败，参数错误[id]'];
            return json($return);
        }

        $sleepModel = new \app\admin\model\Sleep();
        $w = array(
            'uid' => $userInfo['id'],
            'id' => $id,
            'summary_data_ok' => 1,
            'curves_data_ok' => 1,
        );
        $info = $sleepModel->getDataForWhere($w);
        if (!empty($info)) {
            if ($info['curves_data']) {
                $info['curves_data'] = json_decode($info['curves_data'], true);
            } else {
                $info['curves_data'] = array();
            }

            if ($info['summary_data']) {
                $info['summary_data'] = json_decode($info['summary_data'], true);
            } else {
                $info['summary_data'] = array();
            }
            if ($info['curves_data']['data_sleep_status']) {
                $info['deal_data_sleep_status'] = $this->makeDataSleepStatus($info['curves_data']['data_sleep_status']);
            } else {
                $info['deal_data_sleep_status'] = array();
            }
        }

        $return = ['err' => 0, 'msg' => '操作成功', 'data' => $info, 'devMsg' => '操作成功'];
        return json($return);
    }


    /**
     * 睡眠报告详情接口
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function wechatSleepInfo()
    {

        $id = trim(input("request.id"));//报告ID

        $sleepModel = new \app\admin\model\Sleep();
        $w = array(
            'id' => $id,
            'summary_data_ok' => 1,
            'curves_data_ok' => 1,
        );
        $info = $sleepModel->getDataForWhere($w);
        if (!empty($info)) {
            if ($info['curves_data']) {
                $info['curves_data'] = json_decode($info['curves_data'], true);
            } else {
                $info['curves_data'] = array();
            }

            if ($info['summary_data']) {
                $info['summary_data'] = json_decode($info['summary_data'], true);
            } else {
                $info['summary_data'] = array();
            }
            if ($info['curves_data']['data_sleep_status']) {
                $info['deal_data_sleep_status'] = $this->makeDataSleepStatus($info['curves_data']['data_sleep_status']);
            } else {
                $info['deal_data_sleep_status'] = array();
            }
        }

        $return = ['err' => 0, 'msg' => '操作成功', 'data' => $info, 'devMsg' => '操作成功'];
        return json($return);
    }


    public function wechatSleepInfoDefault()
    {

        $id =93;


        $sleepModel = new \app\admin\model\Sleep();
        $w = array(
            'id' => $id
        );
        $info = $sleepModel->getDataForWhere($w);
        if (!empty($info)) {
            if ($info['curves_data']) {
                $info['curves_data'] = json_decode($info['curves_data'], true);
            } else {
                $info['curves_data'] = array();
            }

            if ($info['summary_data']) {
                $info['summary_data'] = json_decode($info['summary_data'], true);
            } else {
                $info['summary_data'] = array();
            }
            if ($info['curves_data']['data_sleep_status']) {
                $info['deal_data_sleep_status'] = $this->makeDataSleepStatus($info['curves_data']['data_sleep_status']);
            } else {
                $info['deal_data_sleep_status'] = array();
            }
        }

        $return = ['err' => 0, 'msg' => '操作成功', 'data' => $info, 'devMsg' => '操作成功'];
        return json($return);
    }


    /**
     * 获取报告接口 [本月睡眠报告][指定月份]
     */
    public function getReport()
    {
        $auth = trim(input("request.auth"));//用户auth
        $userInfo = checkLoginExp($auth);
        $selectDate = trim(input("request.select_date"));//查询月份

        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }
        if (empty($selectDate)) {
            $selectDate = date("Y-m");
        }
        $cacheKey = config("cacheKey.CurrMonthDataKey") . $userInfo['id'] . $selectDate;
        //$lists = getFileCache($cacheKey);
        if (empty($lists)) {
            $currDate = getCurrDate();
            //获取查询月数据
            $lists = $this->getCurrMonthData($userInfo, $selectDate);
            $lists = array(
                'curr_date' => $currDate['simple'],
                'lists' => $lists,
            );
            setFileCache($cacheKey, $lists, $this->expire);
        }
        $return = ['err' => 0, 'msg' => '获取成功', 'data' => $lists];
        return json($return);
    }


    /**
     * 小程序获取指定月份的 报告接口
     * @return \think\response\Json
     */
    public function wechatGetReport()
    {

        $access_token = trim($_REQUEST['access_token']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($_hosp)) {
            $return['err'] = 1;
            $return['msg'] = '参数错误[_hosp]';
            return json($return);
        }
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {

            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $selectDate = trim(input("request.select_date"));//查询月份
        if (empty($selectDate)) {
            $selectDate = date("Y-m");
        }
        $cacheKey = config("cacheKey.CurrMonthDataKey") . $userInfo['id'] . $selectDate;
        //$lists = getFileCache($cacheKey);
        if (empty($lists)) {
            $currDate = getCurrDate();
            //获取查询月数据
            $lists = $this->wechatGetCurrMonthData($userInfo, $selectDate);
            $lists = array(
                'curr_date' => $currDate['simple'],
                'lists' => $lists,
            );
            setFileCache($cacheKey, $lists, $this->expire);
        }
        $return = ['err' => 0, 'msg' => '获取成功', 'data' => $lists];
        return json($return);
    }

    /**
     * 获取报告接口 [最近30天睡眠评分][最近30睡眠时长趋势][最近30入睡时间趋势]
     */
    public function getReportTj()
    {
        $auth = trim(input("request.auth"));//用户auth
        $userInfo = checkLoginExp($auth);

        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }

        $reList = $this->getRecentDays30($userInfo);//获取最近30天的睡眠评分数据
        $lists = array();
        $return = ['err' => 0, 'msg' => '获取成功', 'data' => $reList];
        return json($return);
    }

    /**
     * 获取最近30天的睡眠评分数据
     */
    private function getRecentDays30($userInfo)
    {
        $currDate = getCurrDate();
        $cacheKey = config("cacheKey.RecentDaysData30Key") . $userInfo['id'] . $currDate['simple'];
        //获取查询月数据
        $selectDateSecond = strtotime("-" . ($this->selectDays - 1) . "days");
        $selectDateYear = date("Y", $selectDateSecond);
        $selectDateMonth = date("m", $selectDateSecond);
        $selectDateDay = date("d", $selectDateSecond);
        $selectDate = date("Y-m-d", $selectDateSecond);
        $where = array(
            'uid' => $userInfo['id'],
            'year_month_day' => array('egt', $selectDate),
            'summary_data_ok' => 1,
            'curves_data_ok' => 1,
            'day_ty' => 0,
        );


        $sleepModel = new \app\admin\model\Sleep();
        $fields = "year,month,day,sleep_score,sleep_time,sleep_latency_time,year_month_day";
        $lists = $sleepModel->getDataForWheres($where, $fields, "year asc,month asc,day asc");
        $lists = $this->changeForDateKey($lists);
        $time = time();
        $reList = array();
        $defaultItem = $this->changeDefaultObj($fields);
        for ($i = 0; $i < $this->selectDays; $i++) {
            $ctime = $time;
            if ($i > 0) {
                $ctime = strtotime("-{$i}days", $time);
            }
            $tempYear = date("Y", $ctime);
            $tempMonth = date("m", $ctime);
            $tempDay = date("d", $ctime);
            $tempKey = $this->getDateKey($tempYear, $tempMonth, $tempDay);

            if ($lists[$tempKey]) {
                $reList[] = $lists[$tempKey];
            } else {
                $defaultItem['year'] = (int)$tempYear;
                $defaultItem['month'] = (int)$tempMonth;
                $defaultItem['day'] = (int)$tempDay;
                $defaultItem['year_month_day'] = $tempYear . "-" . $tempMonth . "-" . $tempDay;
                $reList[] = $defaultItem;
            }
        }
        return $reList;
    }

    /**
     * 把一个列表 转换成日期作为下标
     */
    private function changeForDateKey($lists)
    {
        if (empty($lists)) {
            return array();
        }
        $newList = array();
        foreach ($lists as $key => $val) {
            $tempKey = $this->getDateKey($val['year'], $val['month'], $val['day']);
            if ($newList[$tempKey]) {
                if ($newList[$tempKey]['sleep_time'] < $val['sleep_time']) {
                    $newList[$tempKey] = $val;
                }
            } else {
                $newList[$tempKey] = $val;
            }

        }
        return $newList;
    }

    private function getDateKey($year, $month, $day)
    {
        $month = (int)$month;
        $day = (int)$day;
        if ($month < 10) {
            $month = "0" . $month;
        }
        if ($day < 10) {
            $day = "0" . $day;
        }
        return $year . "-" . $month . "-" . $day;
    }


    private function getCurrMonthData($userInfo, $selectDate)
    {
        //获取本月天数
        $totleDays = getMonthDayForYear($selectDate);
        $currDateArray = explode("-", $selectDate);
        //获取本月数据
        $where = array(
            'uid' => $userInfo['id'],
            'year' => $currDateArray[0],
            'month' => $currDateArray[1],
            'summary_data_ok' => 1,
            'curves_data_ok' => 1,
        );

        $sleepModel = new \app\admin\model\Sleep();
        $fields = "year,month,day,sleep_time,sleep_score,depth_sleep_time,depth_sleep_lv,middle_sleep_time,middle_sleep_lv,shallow_sleep_time,shallow_sleep_lv,year_month_day";
        $lists = $sleepModel->getDataForWheres($where, $fields, "day asc");
        $lists = $this->changeForDateKey($lists);

        $reList = array();
        $defaultItem = $this->changeDefaultObj($fields);
        for ($i = 1; $i <= $totleDays; $i++) {
            $tempKey = $this->getDateKey($currDateArray[0], $currDateArray[1], $i);
            if ($lists[$tempKey]) {
                $reList[] = $lists[$tempKey];
            } else {
                $defaultItem['year'] = (int)$currDateArray[0];
                $defaultItem['month'] = (int)$currDateArray[1];
                $defaultItem['day'] = $i;
                $defaultItem['year_month_day'] = $defaultItem['year'] . "-" . ($defaultItem['month'] < 10 ? '0' . $defaultItem['month'] : $defaultItem['month']) . "-" . ($i < 10 ? '0' . $i : $i);
                $reList[] = $defaultItem;
            }
        }
        return $reList;
    }


    private function wechatGetCurrMonthData($userInfo, $selectDate)
    {
        //获取本月天数
        $currDateArray = explode("-", $selectDate);
        //获取本月数据
        $where = array(
            'uid' => $userInfo['id'],
            'year' => $currDateArray[0],
            'month' => $currDateArray[1],
            'summary_data_ok' => 1,
            'curves_data_ok' => 1,
        );

        $sleepModel = new \app\admin\model\Sleep();
        $fields = "id,uid,year_month_day,year,month,day,start_time,end_time,environmental_noise,sleep_latency_time,
        sleep_time,sleep_status,sleep_score,depth_sleep_time,depth_sleep_lv,middle_sleep_time,middle_sleep_lv,
        shallow_sleep_time,shallow_sleep_lv,day_ty,report_ty,fs_count,dream_time,heartrate_argv,heartrate_min,
        heartrate_max,sleepinterruptions_count,turnover_count,dataid,apnea_count,snore_count";
        $lists = $sleepModel->getDataForWheres($where, $fields, "day asc");

        return $lists;
    }

    public function changeDefaultObj($fields)
    {
        if (empty($fields)) {
            return array();
        }
        $retArray = array();
        $array = explode(",", $fields);
        foreach ($array as $k => $v) {
            $retArray[$v] = -1;
        }
        return $retArray;
    }

    public function uploadFiles()
    {
        $filekey = trim(input("request.filekey"));//文件对应的key，原样返回，用于app端 异步上传文件来判断 文件是否上传成功与否
        $auth = trim(input("request.auth"));//用户auth
        $pid = trim(input("request.pid"));//睡眠报告ID
        $ty = trim(input("request.ty"));//1：梦话， 2：鼾声
        $start_time = trim(input("request.start_time"));//开始时间
        $len = trim(input("request.len"));//长度

        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '操作失败,未登录', 'devMsg' => '操作失败，参数错误[auth]'];
            return json($return);
        }

        if (empty($pid)) {
            $return = ['err' => 1, 'msg' => '操作失败', 'devMsg' => '操作失败，参数错误[pid]'];
            return json($return);
        }
        if (empty($ty)) {
            $ty = 1;
        }
        if (empty($filekey)) {
            $filekey = "";
        }
        $scenePic = request()->file('file');
        $path = generaUploadPath($userInfo['id']);
        $resultData = uploadPicture($scenePic, $path);
        $pic = '';
        if ($resultData['err'] == '0') {
            $pic = $resultData['file']['url'];
        }
        $pic = str_replace("\\", "/", $pic);
        $iData = array(
            'url' => $pic,
            'pic' => $pic,
            'thumb' => ""
        );
        $sleepFileModel = new \app\admin\model\SleepFile();
        $fileData = array(
            'uid' => $userInfo['id'],
            'sleep_id' => $pid,
            'url' => $iData['url'],
            'ty' => $ty,
            'start_time' => $start_time,
            'len' => $len,
        );
        $insertId = $sleepFileModel->add($fileData);
        if ($insertId) {
            $return['err'] = 0;
            $return['msg'] = '成功';
            $return['data'] = array('filekey' => $filekey, 'url' => $iData['url']);
            return json($return);
        } else {
            $return['err'] = 10009;
            $return['msg'] = '失败';
            $return['data'] = array('filekey' => $filekey);
            return json($return);
        }
    }

    public function index()
    {
        echo THINK_PATH;
    }

    public function knowledge()
    {
        $type = trim(input("request.type"));
        $img = "";
        switch ($type) {
            case 1:
                $img = "/static/knowledge/knowledge1.png";
                break;
            case 2:
                $img = "/static/knowledge/knowledge2.png";
                break;
            case 3:
                $img = "/static/knowledge/knowledge3.png";
                break;
            case 4:
                $img = "/static/knowledge/knowledge4.png";
                break;
            case 5:
                $img = "/static/knowledge/knowledge5.png";
                break;
            case 6:
                $img = "/static/knowledge/knowledge6.png";
                break;
        }
        $this->assign('img', $img);
        return view('notice');
    }

    public function agreement()
    {
        return view('agreement');
    }


    public function about()
    {
        return view('about');
    }
}
